import Api from "../../../../../utils/api";
import { useState, useEffect, useRef } from "react";
import { Button, Card, Dropdown, Input, Popconfirm, Space, Spin, Table, Tree, Upload, message } from 'antd';
import ScrollTable from '../../../../common/ScrollTable';
import JcdApi from "../../../../../utils/apis/JcdApi";
import _ from 'lodash';
import dynamicColumnApi from "../../../../../utils/apis/dynamicColumnApi";
import { useHistory } from "react-router-dom/cjs/react-router-dom.min";
import FetchHelper from "../../../../../utils/helper/fetch-helper";
import { UploadOutlined } from "@ant-design/icons";

export default function Jcsjxx() {
    const [category, setCategory] = useState();
    const [params, setParams] = useState({
        pageSize: 10,
        pageNum: 1,
        //jcdlx: '雨情'
    });
    const [node, setNode] = useState('雨情');
    const rootRef = useRef();
    useEffect(() => {
        Api.getJcsjCategroy().then(datas => {
            setCategory(datas)
        })
    }, [])
    const [allColumns, setAllColumns] = useState();
    useEffect(() => {
        dynamicColumnApi.jcdjc().then(data => {
            setAllColumns(data);
        })
    }, [])
    const [loading, setLoading] = useState();
    const [datas, setDatas] = useState();
    const [total, setTotal] = useState();
    const [gxData, setGxData] = useState(true);
    const [value, setValue] = useState()
    useEffect(() => {
        setLoading(true);
        let promise;
        if (node?.key === '河道') {
            promise = JcdApi.hdjc_find(params)
        } else if (node === '雨情' || node?.key === '雨情') {
            promise = JcdApi.yqjc_find(params)
        } else if (node?.key === '水库') {
            promise = JcdApi.skjc_find(params)
        } else if (node?.key === '林区卡口') {
            promise = JcdApi.lqkk_find(params)
        } else if (node?.key === '高空瞭望塔') {
            promise = JcdApi.gklwt_find(params)
        } else {
            promise = JcdApi.hljc_find(params)
        }
        promise.then(resp => {
            if (value) {
                const filterData = resp?.rows.filter(item => {
                    if (item?.zdmc) {
                        return item?.zdmc && item?.zdmc.includes(value)
                    } else if (item?.rjyl) {
                        return item?.rjyl && item?.rjyl.includes(value)
                    } else {
                        return item?.dd && item?.dd.includes(value)
                    }
                })
                setDatas(filterData)
            } else {
                setDatas(resp.rows)
            }

            setTotal(resp.total)
        }).finally(e => {
            setLoading(false)
        })
    }, [node, value, gxData,params])

    const tableCols = allColumns?.[node?.key || node] || [];

    // 简化 action 设置
    const actionMap = {
        河道: '/admin-api/ybyj/hdjc/import',
        雨情: '/admin-api/ybyj/yqjc/import',
        水库: '/admin-api/ybyj/skjc/import',
        林区卡口: '/admin-api/ybyj/lqkkjcData/import',
        高空瞭望塔: '/admin-api/ybyj/gklwtjcData/import',
    };

    const props = {
        name: 'file',
        // 使用 node.key 进行查找，默认值为 '/admin-api/ybyj/hljc/import'
        action: actionMap[node?.key] || actionMap['其他'] || '/admin-api/ybyj/hljc/import',
        headers: {
            authorization: 'authorization-text',
        },
        beforeUpload(file) {
            console.log('file', file.type === 'application/vnd.ms-excel')
            const isValidFormat = file.type === 'application/vnd.ms-excel';

            if (!isValidFormat) {
                console.log('file', file.type === 'application/vnd.ms-excel')
                message.error('只能上传 .xls格式的文件!');
            }

            return isValidFormat;
        },
        onChange(info) {
            console.log('node', info)
            if (info.file.status === 'done') {
                if (info.file.response.code !== 200) {
                    message.error( <>
                        {info.file.name} 文件上传失败！<br />
                        错误代码：{info.file.response.msg}<br />
                        可能原因：数据表格可能与本数据表不一致，最好先导出一份数据，使用其模板写入数据后再进行上传
                    </>);
                } else {
                    message.success(`${info.file.name} 文件上传成功`);
                    setGxData(!gxData)
                }

            } else if (info.file.status === 'error') {
                message.error(`${info.file.name} 文件上传失败`);
                message.warning(`数据表格可能与本数据表不一致，最好先导出一份数据，使用其模板写入数据后再进行上传`);
            }
        },
    };




    const history = useHistory();
    ////编辑
    const jcdHandleEdit = (record) => {
        const data = {
            id: record?.id,
            node: node
        }
        history.push({
            pathname: `/manager/jcdEdit/${record.id}`,
            state: data
        })
    }
    //查看
    const jcdHandleLook = (record) => {
        const data = {
            id: record?.id,
            node: node
        }
        history.push({
            pathname: `/manager/jcdLook/${record.id}`,
            state: data
        })
    }
    //删除按键

    const deleteHandle = (record) => {
        console.log('record', record)       
        const endpoints = {
            雨情: `/admin-api/ybyj/yqjc/`,
            水库: `/admin-api/ybyj/skjc/`,
            洪涝: `/admin-api/ybyj/hljc/`,
            林区卡口: `/admin-api/ybyj/lqkkjcData/`,
            高空瞭望塔: `/admin-api/ybyj/gklwtjcData/`,
            河道: `/admin-api/ybyj/hdjc/`,
        };

        let promise;
        const recordId = record?.id;

        // 检查每个属性是否存在并根据第一个找到的属性选择相应的 URL
        const foundKey = Object.keys(endpoints).find(key => {
            console.log('find_key', key,node?.key,key===node?.key) 
            return key === node?.key ? key : false;
        });
        //alert("删除失败！联系开发员解决。")是在endpoints中找不到对应匹配路径，
        const endpoint = foundKey ? endpoints[foundKey] : alert("删除失败！联系开发员解决。");
        promise = FetchHelper.deleteJson(`${endpoint}${recordId}`).then(resp => {
            if (resp.code === 200) {
                message.success(`删除成功！`)
                
            }else{
                message.warning(`删除失败！${resp.msg}`)
            }
        }).catch(e => {
            message.error(`删除失败！${e}`)
        });
        //删除完后触发组件更新
        setGxData(!gxData)
    }
    //新增
    const [keyPath, setKeyPath] = useState('雨情');
    const jcdAddDatas = (keyPath) => {
        // history.push(`/manager/cztAdd/${keyPath[2]}--${keyPath[1]}--${keyPath[0]}`)
        const data = {
            node: node
        }
        history.push({
            pathname: `/manager/jcdAdd/${keyPath}`,
            state: data
        })
    }
    const handleJudge = (node) => {
        setKeyPath(node)
        jcdAddDatas(keyPath)
    }
    useEffect(() => {
        setKeyPath(node)
    }, [node])
    const onSearch = (value) => {
        setValue(value)
        setParams(params => {
            // console.log(params)
            return {
                ...params,
                zdm: value,
                pageNum: 1
            }
        });

    }
    // console.log('datas',datas)

    //导出
    const [url, setUrl] = useState()
    useEffect(() => {
        if (node?.key === '河道') {
            setUrl('/admin-api/ybyj/hdjc/export')
        } else if (node?.key === '雨情') {
            setUrl('/admin-api/ybyj/yqjc/export')
        } else if (node?.key === '水库') {
            setUrl('/admin-api/ybyj/skjc/export')
        } else if (node?.key === '林区卡口') {
            setUrl('/admin-api/ybyj/lqkkjcData/export')
        } else if (node?.key === '高空瞭望塔') {
            setUrl('/admin-api/ybyj/gklwtjcData/export')
        } else {
            setUrl('/admin-api/ybyj/hljc/export')
        }

    }, [node?.key])




    return <div className="layout-h h100">
        <Card size='small' className='h100' style={{
            width: 240,
            marginRight: 12,
            overflowX: "auto",
            overflowY: "auto"
        }} title={"监测数据信息列表"}>
            {category && <Tree className='categray-tree'
                treeData={category} blockNode
                defaultExpandAll
                rootStyle={{ color: '#aaa' }}
                //defaultCheckedKeys={['hd']}
                selectedKeys={[params?.jcdlx]}
                onSelect={(selectedKeys, { node }) => {
                    setNode(node)
                    const p = {}
                    if (node?.children) {
                        p.jcdzl = selectedKeys?.[0]
                    } else {
                        p.jcdlx = selectedKeys?.[0]
                    }
                    setParams(params => {
                        return {
                            pageSize: params.pageSize,
                            pageNum: 1,
                            ...p
                        }
                    })

                }}
                fieldNames={{
                    title: 'title',
                    key: 'title'
                }}
            />}
        </Card>
        <Card size="small" className="h100 fill w0" style={{
            position: "relative",
        }} bodyStyle={{

            display: "flex",
            flexDirection: "column",
            height: "100%"
        }}>
            <div style={{
                marginBottom: 12,
                display: 'flex',
                alignItems: "center",
                justifyContent: "space-between"
            }}>

                <Space>
                    <>
                        {/* <Button onClick={() => handleJudge(node)}>新增</Button> */}
                        <Upload {...props}>
                            <Button icon={<UploadOutlined />}>数据导入</Button>
                        </Upload>
                        {/* <Button type="primary" key="download" onClick={() => {
                            const params = {
                                "id": datas?.id,
                                "deleted": datas?.deleted,
                                "czry": datas?.czry,
                                "lrr": datas?.lrr,
                                "lrsj": datas?.lrsj,
                                "sfxg": datas?.sfxg,
                                "tbr": datas?.tbr,
                                "tbrdh": datas?.tbrdh,
                                "zhxgsj": datas?.zhxgsj,
                                "zrr": datas?.zrr,
                                "zrrdh": datas?.zrrdh,
                                "gd": datas?.gd,
                                "geom": datas?.geom,
                                "jcdlx": datas?.jcdlx,
                                "jcjjx": datas?.jcjjx,
                                "jd": datas?.jd,
                                "wd": datas?.wd,
                                "xq": datas?.xq,
                                "zddz": datas?.zddz,
                                "zdid": datas?.zdid,
                                "zdm": datas?.zdm,
                                "tyshxydm": datas?.tyshxydm,
                                "xzqhbm": datas?.xzqhbm,
                                "xzqhmc": datas?.xzqhmc,
                                "yzzjgdm": datas?.yzzjgdm
                            }
                            fetch(url, {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json;charset=UTF-8'
                                },
                                body: JSON.stringify(params),
                                redirect: "follow"
                            }).then(response => response.blob()).then(blob => {
                                // debugger
                                const a = document.createElement("a");
                                a.download = "data.zip";
                                a.href = URL.createObjectURL(blob);
                                a.click();
                            }).catch(error => console.log(error))
                        }}>数据导出</Button> */}
                    </>
                </Space>

                <div>
                    <Input.Search placeholder='输入名称查找'
                        allowClear
                        enterButton={true}
                        onSearch={onSearch}
                    />
                </div>
            </div>
            <div ref={rootRef} className="fill h0">
                <ScrollTable style={{
                }}
                    loading={loading}
                    parentNode={rootRef.current}
                    size='small'
                    bordered
                    dataSource={datas}
                    scroll={{
                        x: 320 + _.sumBy(tableCols, 'width'),
                    }}
                    columns={[
                        ...tableCols,
                        {
                            title: '操作',
                            key: 'caozuo',
                            width: 260,
                            fixed: "right",
                            render: (text, record) => {
                                return <Space size="middle">
                                    {/* <Button onClick={e => { jcdHandleLook(record) }}>查看</Button>

                                    <Button onClick={e => { jcdHandleEdit(record) }}>编辑</Button> */}

                                    <Popconfirm title="确定删除吗?" onConfirm={e => deleteHandle(record)}>
                                        {/* <Button onComfir={e => { deleteHandle(record) }}>删除</Button> */}
                                        <Button>删除</Button>
                                    </Popconfirm>
                                </Space>

                            }
                        },

                    ]
                        .map(item => {
                            return {
                                ...item,
                                // ellipsis: {
                                //     showTitle: false
                                // }
                            }
                        })
                    }

                    pagination={{
                        current: params.pageNum,
                        pageSize: params.pageSize,
                        total,

                        // simple: true
                    }}
                    onChange={({ current }) => {
                        setParams(params => {
                            return {
                                ...params,
                                pageNum: current
                            }
                        })
                    }}
                // size='small'
                />
            </div>
        </Card>


    </div>

}